using BuildingBlocks.Application.Messaging;  
using BuildingBlocks.Domain;  
using Catalog.Api.Data;  
using Catalog.Api.Models;  
using MongoDB.Driver;  
  
namespace Catalog.Api.Features.CatalogItems.DeleteCatalogItem;  
  
public sealed record DeleteCatalogItemCommand(string Id) : ICommand;  
  
internal sealed class DeleteCatalogItemCommandHandler(CatalogDbContext context)  
    : ICommandHandler<DeleteCatalogItemCommand>  
{  
    public async ValueTask<Result> Handle(DeleteCatalogItemCommand request, CancellationToken cancellationToken)  
    {  
        var filter = Builders<CatalogItem>.Filter.Eq(i => i.Id, request.Id);  
        var item = await context.CatalogItems.Find(filter).FirstOrDefaultAsync(cancellationToken);  
  
        if (item is null)  
        {  
            return Result.Failure(CatalogItemErrors.NotFound(request.Id));  
        }  
  
        await context.CatalogItems.DeleteOneAsync(filter, cancellationToken);  
  
        return Result.Success();  
    }  
}
